
// get data by type
$app->get( '/data_by_name/:name', function( $name ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
    $data = array();
    foreach( $db->data()->where( 'NAME', $name ) as $result ) {
        $data[] = array(
            'id'         => $result['DID'],
            'parent'      => $result['PARENT'],
			'tag'      => $result['TAG'],
			'name'      => $result['NAME'],
			'description'      => $result['DESCRIPTION'],
			'type'      => $result['TYPE'],
			'measurement'      => $result['MEASUREMENT'],
			'value'      => $result['VALUE'],
			'location'      => $result['LOCATION'],
			'datecreated'      => $result['DATECREATED'],			
			'quantity'      => $result['QUANTITY'],
        );
    }
	
	//print_r($data);
	 // echo json_encode( $data, JSON_FORCE_OBJECT );
	 // echo json_encode( array('message' => 'DID INE: '.$data[0]['id'] ) );
	 // echo ;
	//If the type is orders we need to calculate the value on the fly 
	 /*$val = 0;
	 $current_id = $data[0]['id'];
	 echo  $current_id;
	foreach( $db->datadetail()->where( 'PARENT',  $current_id  ) as $result )  {
		$val = $val +  $result['val'] ;
		$data[0]['value'] = $val ;
	 } */
	

      echo json_encode( $data, JSON_FORCE_OBJECT );
});


// get existing programs 
$app->get( '/existing/:type', function( $type ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
    $data = array();
	
	#count
    foreach( $db->data()->where( 'TYPE', $type ) as $result ) {
		$program = $result['DID'];
       
		
		//If there is a child here we should get it going here 
					$program_outputs = array();
					foreach( $db->data()->where(array("TYPE"=>'output',"PARENT"=>$program ) ) as $outputs ) {
					
					
					//Here we dig in the inputs for each of the outputs 
					
								$output_inputs = array();
								foreach( $db->datadetail()->where( 'PARENT',$outputs['DID'] ) as $inputs ) {
								
								foreach( $db->data()->where( 'DID',$inputs['ITEM'] ) as $parent ) {
									
									$input = array(
									'id'         => $inputs['DID'], 
									'text'      => $parent['NAME'],  
									'icon'      => 'jstree-file', 
									);
								
								}
								
								
								
								//Here we dig in the inputs for each of the outputs 
								
								array_push($output_inputs,$input);
							}
							
											if (empty($output_inputs)){
												$output = array(
													'id'         => 'output-'.$outputs['DID'].'-'.$result['DID'], 
													'text'      => $outputs['NAME'], 
												);
											}else {
												$output = array(
													'id'         => 'output-'.$outputs['DID'].'-'.$result['DID'], 
													'text'      => $outputs['NAME'], 
													'children'      => $output_inputs, 
													 
												);
											}
			
					
					
					array_push($program_outputs,$output);
				}
		
			if (empty($program_outputs)){
				
				
				 $item = array(
					
					'id'         =>'program-'.$result['DID'], 
					'text'      => $result['NAME'], 
					'type'      => 'child',  
				);
			}else {
				$item = array(
					'id'         => 'program-'.$result['DID'], 
					'text'      => $result['NAME'], 
					'children'      => $program_outputs, 
					'type'      => 'child',  
					
				);
			}
				array_push($data,$item);
    }
	
	//print_r($data);
	 // echo json_encode( $data, JSON_FORCE_OBJECT );
	 // echo json_encode( array('message' => 'DID INE: '.$data[0]['id'] ) );
	 // echo ;
	//If the type is orders we need to calculate the value on the fly 
	 /*$val = 0;
	 $current_id = $data[0]['id'];
	 echo  $current_id;
	foreach( $db->datadetail()->where( 'PARENT',  $current_id  ) as $result )  {
		$val = $val +  $result['val'] ;
		$data[0]['value'] = $val ;
	 } */
	
 $final = array(
            'id'         => 0, 
			'text'      => 'All Programs', 
			'children'      =>  $data, 
			'type'      => 'root', 
        );
      echo json_encode( $final);
});

// get data by type
$app->get( '/data_by_type/:type', function( $type ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
    $data = array();
    foreach( $db->data()->where( 'TYPE', $type ) as $result ) {
        $data[] = array(
            'id'         => $result['DID'],
            'parent'      => $result['PARENT'],
			'tag'      => $result['TAG'],
			'name'      => $result['NAME'],
			'description'      => $result['DESCRIPTION'],
			'type'      => $result['TYPE'],
			'measurement'      => $result['MEASUREMENT'],
			'value'      => $result['VALUE'],
			'location'      => $result['LOCATION'],
			'datecreated'      => $result['DATECREATED'],			
			'quantity'      => $result['QUANTITY'],
        );
    }
	
	//print_r($data);
	 // echo json_encode( $data, JSON_FORCE_OBJECT );
	 // echo json_encode( array('message' => 'DID INE: '.$data[0]['id'] ) );
	 // echo ;
	//If the type is orders we need to calculate the value on the fly 
	 /*$val = 0;
	 $current_id = $data[0]['id'];
	 echo  $current_id;
	foreach( $db->datadetail()->where( 'PARENT',  $current_id  ) as $result )  {
		$val = $val +  $result['val'] ;
		$data[0]['value'] = $val ;
	 } */
	

      echo json_encode( $data, JSON_FORCE_OBJECT );
});

// get data by type
$app->get( '/data_by_typeid/:type', function( $type ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
	//print_r($app->request);
	$parent = $app->request->get('parent');
	
	
	
    $data = array();
    foreach( $db->data()->where(array("TYPE"=>$type,"PARENT"=>$parent )) as $result ) {
        $data[] = array(
            'id'         => $result['DID'],
            'parent'      => $result['PARENT'],
			'tag'      => $result['TAG'],
			'name'      => $result['NAME'],
			'description'      => $result['DESCRIPTION'],
			'type'      => $result['TYPE'],
			'measurement'      => $result['MEASUREMENT'],
			'value'      => $result['VALUE'],
			'location'      => $result['LOCATION'],
			'datecreated'      => $result['DATECREATED'],
			'quantity'      => $result['QUANTITY'],
        );
    }

    echo json_encode( $data, JSON_FORCE_OBJECT );
});


$app->get( '/data_by_name/:name', function( $type ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
	//print_r($app->request);
	$parent = $app->request->get('name');
	
	
	
    $data = array();
    foreach( $db->data()->where( 'NAME LIKE ?', '%'.$id.'%' ) as $result ) {
        $data[] = array(
            'id'         => $result['DID'],
            'parent'      => $result['PARENT'],
			'tag'      => $result['TAG'],
			'name'      => $result['NAME'],
			'description'      => $result['DESCRIPTION'],
			'type'      => $result['TYPE'],
			'measurement'      => $result['MEASUREMENT'],
			'value'      => $result['VALUE'],
			'location'      => $result['LOCATION'],
			'datecreated'      => $result['DATECREATED'],
			'quantity'      => $result['QUANTITY'],
        );
    }

    echo json_encode( $data, JSON_FORCE_OBJECT );
});


// get data by id
$app->get( '/data_by_id/:id', function( $id ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
    $data = array();
	
	//echo ' Ndati id ine: '.$id;
	
    foreach( $db->data()->where( 'DID', $id ) as $result ) {
        $data[] = array(
            'id'         => $result['DID'],
            'parent'      => $result['PARENT'],
			'tag'      => $result['TAG'],
			'name'      => $result['NAME'],
			'description'      => $result['DESCRIPTION'],
			'type'      => $result['TYPE'],
			'measurement'      => $result['MEASUREMENT'],
			'value'      => $result['VALUE'],
			'location'      => $result['LOCATION'],
			'datecreated'      => $result['DATECREATED'],
			'quantity'      => $result['QUANTITY'],
        );
    }

    echo json_encode( $data, JSON_FORCE_OBJECT );
});

// delete data detail by id
$app->get( '/delete_detail_by_id/:id', function( $id ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
 
	
	if ( $result = $db->datadetail("DID", $id)->delete() ) {
					
						echo json_encode( array('message' => 'Data successfully deleted!' ) );
						
					} else {
						echo json_encode( array( 'message' => 'data not deleted')  );
					}
  
});

// get data by id
$app->get( '/datadetail_by_id/:id', function( $id ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
    $data = array(); 
	
	//echo ' Ndati id ine: '.$id;
	
    foreach( $db->datadetail()->where( 'PARENT', $id ) as $result ) {
	
	//print_r($result);
	
        $data[] = array(
            'id'        => $result['DID'],
            'parent'    => $result['PARENT'],
			'value'     => $result['VALUE'],
			'quantity'  => $result['QUANTITY'],
			'item'      => $result['ITEM'],
			'type'      => $result['TYPE'],
			'completed'      => $result['COMPLETED'],
			/*'measurement'      => $result['MEASUREMENT'],
			'value'      => $result['VALUE'],
			'location'      => $result['LOCATION'],
			'datecreated'      => $result['DATECREATED'],*/
        );
    }
	
    echo json_encode( $data, JSON_FORCE_OBJECT );
});

 $app->get( '/jointest/:id', function( $id ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
    $data = array(); 
	
	//echo ' Ndati id ine: '.$id;
	
 foreach ($db->data()->datadetail("data.did") as $application) {
    echo $application->data["name"] ;
}
	
  //  echo json_encode( $data, JSON_FORCE_OBJECT );
});

// get data by id
$app->get( '/datadetail/:id', function( $id ) use( $app, $db ) {
    $app->response()->header("Content-Type", "application/json");
    $data = array(); 
	
	//echo ' Ndati id ine: '.$id;
	
    foreach( $db->datadetail()->where( 'PARENT', $id ) as $result ) {
	
	//print_r($result);
	
        $data[] = array(
            'id'        => $result['DID'],
            'parent'    => $result['PARENT'],
			'value'     => $result['VALUE'],
			'quantity'  => $result['QUANTITY'],
			'item'      => $result['ITEM'],
			'type'      => $result['TYPE'],
			'completed'      => $result['COMPLETED'],
			/*'measurement'      => $result['MEASUREMENT'],
			'value'      => $result['VALUE'],
			'location'      => $result['LOCATION'],
			'datecreated'      => $result['DATECREATED'],*/
        );
    }
	
    echo json_encode( $data, JSON_FORCE_OBJECT );
});

function createProgramChild(){

}

//create data item  
$app->post( '/create_data', function() use( $app, $db ) {
	$app->response()->header( "Content-Type", "application/json" );
	$data = $app->request()->post();
	
	$type = $app->request->post('type');
	$parent = $app->request->post('parent');
	$quantity = $app->request->post('quantity');
	$value = $app->request->post('value');
	
	//print_r($app->request()->post());
	
	//echo $app->request->get('id');
	
	if ($app->request->post('did') > 0){
	
		 //Input a data detail here cause the parent already exist e.g. if program is A and we are doing an output for it that exists. Put an an entry in data detail with program as the parent and output as the child.
		$data = array_merge($data, array("id"=> $data['did']));
		 	echo json_encode( $data);
		 
	}
	
	else{
		if ( $result = $db->data->insert($data) ) {
			
					$item = '';
				 
	 
			
			
				try {
						//print_r($result);
						echo json_encode( $result);
						
						//echo json_encode( array('id' => $result[7] ,'message' => 'New data successfully saved!' ) );
					} catch (Exception $e) {
						//print_r($result);
						//echo json_encode( array('id' => $result[7] ,'message' => 'New data successfully saved!' ) );
					echo json_encode( $result);
						die();
					}
			 
		} else {
			echo json_encode( array( 'message' => 'data not created')  );
		}
	}
	




});


//update data item  
$app->post( '/update_data', function() use( $app, $db ) {
	$app->response()->header( "Content-Type", "application/json" );
	$data = $app->request()->post();
	
	//print_r($app->request()->post());
	
	//echo $app->request->get('id');
	
	//if ($app->request->post('did') > 0){
	
		 $row = $db->data()->where("DID", $app->request->post('did'));
		 
		// echo json_encode( array('message' => $row) );
		
			if ($row->fetch()) {
				
					if ( $result = $row->update($data) ) {
					
						echo json_encode( array('message' => 'Data successfully updated!' ) );
						
					} else {
					
						echo json_encode( array( 'message' => 'data not updated')  );
						
					}
			}else {
				echo json_encode( array('message' => $app->request->post('did')) );
			}
	 
	
 



});


//add data item  detail
$app->post( '/datadetail', function() use( $app, $db ) {
	$app->response()->header( "Content-Type", "application/json" );
	$data = $app->request()->post();
	
	//print_r($app->request()->post());
	
	//echo $app->request->get('id');
	
	if ($app->request->post('id') > 0){
	
	//UPDATE THE ROW QUANTITIES
	
		 $row = $db->datadetail()->where("ID", $app->request->post('id'));
		// echo json_encode( array('message' => $row) );
			if ($row->fetch()) {
				
					if ( $result = $row->update($data) ) {
					
						echo json_encode( array('message' => 'Details successfully updated!' ) );
						
					} else {
						echo json_encode( array( 'message' => 'Details not updated')  );
					}
			}else {
				echo json_encode( array('message' => $app->request->post('id')) );
			}
	}
	
	else{
		if ( $result = $db->datadetail->insert($data) ) {
			echo json_encode( array('message' => 'Details successfully saved!' ) );
		} else {
			echo json_encode( array( 'message' => 'Details not created')  );
		}
	}
	
 



});

